import { getUserInfo } from "@/api/user"

// 用户模块
export default {
  namespaced: true,
  state () {
    return {
      // 用户信息
      profile: {
        id: '',
        avatar: '',
        nickname: '',
        account: '',
        mobile: '',
        token: '',
        user_phone: '',
        mch: null, // 1 - 已入驻 0 - 未入驻
        id_role: null // 0- 管理员
      },
      invoice: [], // 储存发票信息
      default_invoice: {}, // 
      default_address: {} // 默认的地址
    }
  },
  mutations: {
    // 修改用户信息，payload就是用户信息对象
    setUser (state, payload) {
      state.profile = payload
    },
    refreshToken (state, payload) {
      state.profile.token = payload
    },
    // 合并账号信息 和登入 信息
    mergeInfo (state, payload) {
      state.profile = { ...state.profile, ...payload }
    },
    // 设置发票信息
    serInvoice (state, payload) {
      state.invoice = payload
    },
    // 储存默认的地址
    setDefaultAddress (state, payload) {
      state.default_address = payload
    },
    serDefaultInvoice (state, payload) {
      state.default_invoice = payload
    },
    // 清空登入信息
    clearInfo (state) {
      state.invoice = {}
      state.default_invoice = {}
      state.default_address = {}
      state.profile = {}
    }
  },
  actions: {
    // 获取账号信息
    async getInfo (store) {
      if (store.rootState.user.profile.token) {
        const res = await getUserInfo()
        store.commit('mergeInfo', res.data)
      }
    }
  },
  getters: {
    userinfo (state) {
      return state.profile
    },
    invoice (state) {
      return state.invoice
    },
    address: (state) => state.default_address,
    default_invoice: (state) => state.default_invoice
  }
}
